﻿using Dx.DDD.Domain.Entities;
using Dx.Shared;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using System.Linq.Expressions;

namespace Dx.DDD.Repositories
{
    public static class EntityExtension
    {

        public static void ConfigureConcurrencyStamp<T>(this EntityTypeBuilder<T> b)
            where T : class, IHasConcurrencyStamp
        {
            b.Property(x=>x.ConcurrencyStamp).HasMaxLength(40).IsConcurrencyToken();
        }


        public static IQueryable<T> WhereIf<T>(this IQueryable<T> query, bool condition, Expression<Func<T, bool>> predicate)
        {
            Check.NotNull(query, "query");
            if (!condition)
            {
                return query;
            }

            return query.Where(predicate);
        }

        /// <summary>
        /// 分页查询
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="query"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public static IQueryable<T> PageByIndex<T>(this IQueryable<T> query, int pageIndex, int pageSize)
        {
            //Check.NotNull(query, nameof(query));
            if (query is null) throw new Exception(nameof(query) + "is null");
            if (pageIndex <= 0)
            {
                pageIndex = 1;
            }
            if (pageSize <= 0)
            {
                pageSize = 10;
            }
            return query.Skip((pageIndex - 1) * pageSize).Take(pageSize);
        }
    }
}
